//
//  MainSubLiteratureViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/19.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "LiteratureViewController.h"

#import "TotalSearchViewController.h"
#import "AddrChooserViewController.h"
#import "StwxDetailViewController.h"
#import "DocumentDetailViewController.h"

#import "EPMainTabsView.h"

#import "ZCFGCell.h"
#import "DocumentV2Cell.h"

#import "ArticleListData.h"

@interface LiteratureViewController () <UITableViewDelegate, UITableViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) LiteratureViewModel* viewModel;

@property (nonatomic, copy) NSArray* tableViews;

// UI
@property (weak, nonatomic) UILabel* addressLabel;
@property (weak, nonatomic) UILabel* searchLabel;
@property (weak, nonatomic) UIButton* searchButton;
@property (weak, nonatomic) UIButton* addressButton;

//IBOutlet
@property (weak, nonatomic) IBOutlet UIView* tabsView;
@property (weak, nonatomic) IBOutlet UIScrollView* tableScrollView;

@end

@implementation LiteratureViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self _setupAllViewInViewLoad];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:[willAppearSignal replay]] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    RACSignal* addressChangeSignal = [RACObserve(self.viewModel, zone) distinctUntilChanged];
    RAC(self.addressLabel, text) = [[addressChangeSignal replay] map:^id(id value)
                                    {
                                        NSString* strResult = value;
                                        
                                        strResult = HCStrFormat(@"%@ >", strResult);
                                        
                                        return strResult;
                                    }];
}

- (void)_setupAllViewInViewLoad
{
    @weakify(self);
    
    // 返回按钮置换
    CGRect textRect = [self.viewModel.cateName boundingRectWithSize:CGSizeMake(MAXFLOAT, 44.0f)
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}
                                                            context:nil];
    
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:MHImageNamed(@"icon_back_hei") forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 12.0f, 0, 0);
    [backBtn setTitle:self.viewModel.cateName forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(_onBtnBack) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = (CGRect) {0, 0, 18 + 4.0f + textRect.size.width, 44};
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    // 搜索栏
    UIView* searchView = [[UIView alloc] initWithFrame:(CGRect) {0, (44 - 28)/2.0f, 88, 28}];
    searchView.backgroundColor = UIColorHex(#f0f0f0);
    searchView.layer.cornerRadius = 5.0f;
    searchView.layer.masksToBounds = YES;
    UILabel* searchLabel = [[UILabel alloc] initWithFrame:(CGRect) {4 + 28, 0, 88-28-8, 28}];
    searchLabel.text = @"点击搜索";
    searchLabel.font = [UIFont systemFontOfSize:12.0f];
    searchLabel.textColor = UIColorHex(#999999);
    [searchView addSubview:searchLabel];
    self.searchLabel = searchLabel;
    UIButton* searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = (CGRect) {4, 0, 28, 28};
    [searchBtn setImage:[UIImage imageNamed:@"icon_graySearch"] forState:UIControlStateNormal];
    searchBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [searchView addSubview:searchBtn];
    UIButton* bsearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    bsearchBtn.frame = (CGRect) {0, 0, searchView.frame.size};
    bsearchBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [bsearchBtn addTarget:self action:@selector(_onBtnSearch) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:bsearchBtn];
    self.searchButton = bsearchBtn;
    
    UIView* titleView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 88, 44}];
    [titleView addSubview:searchView];
    self.navigationItem.titleView = titleView;
    
    // 地区按钮
    UIView* cityView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 0, 64}];
    
    UILabel* cityLabel = [[UILabel alloc] initWithFrame:(CGRect) {0, 0, 0, 44}];
    cityLabel.text = @"汕头市 >";
    cityLabel.textColor = Color_MainGreen;
    cityLabel.font = [UIFont systemFontOfSize:14.0f];
    cityLabel.textAlignment = NSTextAlignmentRight;
    [cityView addSubview:cityLabel];
    
    UIImageView* cityArrowImg = [[UIImageView alloc] initWithFrame:(CGRect) {0, 12, 22, 27}];
    cityArrowImg.image = [UIImage imageNamed:@"icon_location"];
    cityArrowImg.contentMode = UIViewContentModeCenter;
    [cityView addSubview:cityArrowImg];
    
    UIButton* cityBtn = [[UIButton alloc] initWithFrame:(CGRect) {0, 0, 0, 44}];
    [[cityBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self _push2AddrPop];
     }];
    [cityView addSubview:cityBtn];
    
    [cityLabel mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.height.mas_equalTo(44);
         
         make.left.mas_equalTo(cityArrowImg.mas_right);
         make.top.mas_equalTo(0);
         make.bottom.mas_equalTo(0);
         make.right.mas_equalTo(0);
     }];
    
    [cityArrowImg mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.height.mas_equalTo(22);
         make.width.mas_equalTo(27);
         
         make.left.mas_equalTo(0);
         make.right.mas_equalTo(cityLabel.mas_left).mas_offset(0);
         make.top.mas_equalTo(0);
         make.bottom.mas_equalTo(0);
     }];
    
    [cityBtn mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.left.mas_equalTo(0);
         make.right.mas_equalTo(0);
         make.top.mas_equalTo(0);
         make.bottom.mas_equalTo(0);
     }];
    
    [cityView mas_remakeConstraints:^(MASConstraintMaker *make)
     {
         make.height.mas_equalTo(64);
     }];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:cityView];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.addressLabel = cityLabel;
    self.addressButton = cityBtn;
    
    // 标签页判断
    for (NSLayoutConstraint* constraint in self.tabsView.constraints)
    {
        if (constraint.firstAttribute == NSLayoutAttributeHeight)
        {
            constraint.constant = self.viewModel.tabViewHeight;
            
            break;
        }
    }
}

- (void)_setupAllView
{
    [self _setupTabsView];
    [self _setupTableScrollView];
}

- (void)_setupTabsView
{
    @weakify(self)
    
    CGSize tabContentScrollViewSize = self.tableScrollView.frame.size;
    
    NSMutableArray* tabInfos = [NSMutableArray array];
    for (NSInteger index=0; index<self.viewModel.cateInfoData.cateList.count; index++)
    {
        CateInfoData* cateInfoData = self.viewModel.cateInfoData.cateList[index];
        
        [tabInfos addObject:@{@"TabName":cateInfoData.cateName}];
    }
    
    EPMainTabsViewModel* vm = [[EPMainTabsViewModel alloc] init];
    vm.tabInfos = tabInfos;
    [vm.didClickTab subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSLog(@"TabsView select index : %d", [x integerValue]);
         
         NSInteger index = [x integerValue];
         
         self.viewModel.tabIndex = index;
         
         [self.tableScrollView scrollRectToVisible:(CGRect) {index*tabContentScrollViewSize.width, 0, tabContentScrollViewSize} animated:YES];
     }];
    
    EPMainTabsView* curView = [[EPMainTabsView alloc] initWithFrame:(CGRect) {0, 0, self.tabsView.frame.size}];
    [curView bindViewModel:vm];
    curView.tag = 99;
    [self.tabsView addSubview:curView];
}

- (void)_setupTableScrollView
{
    @weakify(self);
    
    NSMutableArray* newTableViews = [NSMutableArray array];
    
    NSInteger tCount = self.viewModel.tableVMs.count;
    for (NSInteger index=0; index<tCount; index++)
    {
        if (self.viewModel.tvmType == 0)
        {
            ZCFGV2TableViewModel* curTableVM = self.viewModel.tableVMs[index];
            
            [[[[RACObserve(curTableVM, dataSource) distinctUntilChanged] filter:^BOOL(id value) {
                
                return value != nil;
            }] deliverOnMainThread]
             subscribeNext:^(id x) {
                 @strongify(self)
                 // 刷新数据
                 
                 NSArray* curArr = x;
                 UITableView* curTableView = self.tableViews[index];
                 UIImageView* emptyTipView = [curTableView viewWithTag:199];
                 emptyTipView.hidden = curArr.count > 0;
                 
                 [self reloadListData:curTableVM.tag];
             }];
            
            curTableVM.didSelectCommand = curTableVM.selectCmd;
            
            [[curTableVM.selectCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
                @strongify(self)
                
                ArticleListData* listData = x;
                
                [self _push2StwxDetailVCByArticleID:listData.articleID type:listData.type];
            }];
            
            UITableView* tableView = [[UITableView alloc] initWithFrame:(CGRect){index*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - self.viewModel.tabViewHeight}];
            tableView.tag = 10 + index;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            tableView.delegate = self;
            tableView.dataSource = self;
            
            /// 添加加载和刷新控件
            if (curTableVM.shouldPullDownToRefresh) {
                /// 下拉刷新
                [tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
                    /// 加载下拉刷新的数据
                    @strongify(self);
                    [self tableViewDidTriggerHeaderRefresh:curTableVM];
                }];
                [tableView.mj_header beginRefreshing];
            }
            
            if (curTableVM.shouldPullUpToLoadMore) {
                /// 上拉加载
                @weakify(self);
                [tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
                    /// 加载上拉刷新的数据
                    @strongify(self);
                    [self tableViewDidTriggerFooterRefresh:curTableVM];
                }];
                
                /// 判断一下数据
                [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:curTableVM];
            }
            
#ifdef __IPHONE_11_0
            MHAdjustsScrollViewInsets_Never(tableView);
            tableView.estimatedRowHeight = 0;
            tableView.estimatedSectionHeaderHeight = 0;
            tableView.estimatedSectionFooterHeight = 0;
#endif
            
            [tableView mh_registerNibCell:[ZCFGCell class]];
            
            UIImage* emptyTipImg = MHImageNamed(@"baocuo");
            UIImageView* emptyTipView = [[UIImageView alloc] initWithImage:emptyTipImg];
            emptyTipView.hidden = YES;
            CGPoint centerPoint = (CGPoint) {self.view.frame.size.width/2.0f, self.view.frame.size.height/2.0f + 22.0f};
            CGSize viewSize = (CGSize) {100, emptyTipImg.size.height*100/emptyTipImg.size.width};
            emptyTipView.frame = (CGRect) {centerPoint.x - viewSize.width/2.0f, centerPoint.y - viewSize.height/2.0f, viewSize};
            emptyTipView.tag = 199;
            UILabel* tipLabel = [[UILabel alloc] initWithFrame:(CGRect) {16, viewSize.height + 24, viewSize.width, 24}];
            tipLabel.text = @"暂无记录";
            tipLabel.textColor = UIColorHex(#bbbbbb);
            [emptyTipView addSubview:tipLabel];
            [tableView addSubview:emptyTipView];
            
            [self.tableScrollView addSubview:tableView];
            
            [newTableViews addObject:tableView];
        }
        else
        {
            DocumentV2TableViewModel* curTableVM = self.viewModel.tableVMs[index];
            
            [[[[RACObserve(curTableVM, dataSource) distinctUntilChanged] filter:^BOOL(id value) {
                
                return value != nil;
            }] deliverOnMainThread]
             subscribeNext:^(id x) {
                 @strongify(self)
                 // 刷新数据
                 
                 NSArray* curArr = x;
                 UITableView* curTableView = self.tableViews[index];
                 UIImageView* emptyTipView = [curTableView viewWithTag:199];
                 emptyTipView.hidden = curArr.count > 0;
                 
                 [self reloadListData:curTableVM.tag];
             }];
            
            curTableVM.didSelectCommand = curTableVM.selectCmd;
            
            [[curTableVM.selectCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
                @strongify(self)
                
                ArticleListData* listData = x;
                
                [self _push2StwxDetailVCByArticleID:listData.articleID type:listData.type];
            }];
            
            UITableView* tableView = [[UITableView alloc] initWithFrame:(CGRect){index*self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height - self.viewModel.tabViewHeight}];
            tableView.tag = 10 + index;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            tableView.delegate = self;
            tableView.dataSource = self;
            
            /// 添加加载和刷新控件
            if (curTableVM.shouldPullDownToRefresh) {
                /// 下拉刷新
                [tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
                    /// 加载下拉刷新的数据
                    @strongify(self);
                    [self tableViewDidTriggerHeaderRefresh:curTableVM];
                }];
                [tableView.mj_header beginRefreshing];
            }
            
            if (curTableVM.shouldPullUpToLoadMore) {
                /// 上拉加载
                @weakify(self);
                [tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
                    /// 加载上拉刷新的数据
                    @strongify(self);
                    [self tableViewDidTriggerFooterRefresh:curTableVM];
                }];
                
                /// 判断一下数据
                [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:curTableVM];
            }
            
#ifdef __IPHONE_11_0
            MHAdjustsScrollViewInsets_Never(tableView);
            tableView.estimatedRowHeight = 0;
            tableView.estimatedSectionHeaderHeight = 0;
            tableView.estimatedSectionFooterHeight = 0;
#endif
            
            [tableView mh_registerNibCell:[DocumentV2Cell class]];
            
            UIImage* emptyTipImg = MHImageNamed(@"baocuo");
            UIImageView* emptyTipView = [[UIImageView alloc] initWithImage:emptyTipImg];
            emptyTipView.hidden = YES;
            CGPoint centerPoint = (CGPoint) {self.view.frame.size.width/2.0f, self.view.frame.size.height/2.0f + 22.0f};
            CGSize viewSize = (CGSize) {100, emptyTipImg.size.height*100/emptyTipImg.size.width};
            emptyTipView.frame = (CGRect) {centerPoint.x - viewSize.width/2.0f, centerPoint.y - viewSize.height/2.0f, viewSize};
            emptyTipView.tag = 199;
            UILabel* tipLabel = [[UILabel alloc] initWithFrame:(CGRect) {16, viewSize.height + 24, viewSize.width, 24}];
            tipLabel.text = @"暂无记录";
            tipLabel.textColor = UIColorHex(#bbbbbb);
            [emptyTipView addSubview:tipLabel];
            [tableView addSubview:emptyTipView];
            
            [self.tableScrollView addSubview:tableView];
            
            [newTableViews addObject:tableView];
        }
    }
    self.tableViews = newTableViews;
    
    self.tableScrollView.contentSize = (CGSize) {tCount*self.view.frame.size.width, self.view.frame.size.height - self.viewModel.tabViewHeight};
    self.tableScrollView.pagingEnabled = YES;
    self.tableScrollView.alwaysBounceVertical = NO;
    self.tableScrollView.alwaysBounceHorizontal = NO;
    self.tableScrollView.delegate = self;
}

#pragma mark -- sub class can override it
/// 下拉事件
- (void)tableViewDidTriggerHeaderRefresh:(id)tvm
{
    @weakify(self)
    NSDictionary* info = @{@"LoadIndex":@(0)};
    
    if (self.viewModel.tvmType == 0)
    {
        ZCFGV2TableViewModel* tableVM = tvm;
        [[[tableVM.requestDataCmd
           execute:info]
          deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             tableVM.page = 1;
         } error:^(NSError *error) {
             @strongify(self)
             [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
         } completed:^{
             @strongify(self)
             /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据
             [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
         }];
    }
    else
    {
        DocumentV2TableViewModel* tableVM = tvm;
        [[[tableVM.requestDataCmd
           execute:info]
          deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             tableVM.page = 1;
         } error:^(NSError *error) {
             @strongify(self)
             [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
         } completed:^{
             @strongify(self)
             /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据
             [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
         }];
    }
}

/// 上拉事件
- (void)tableViewDidTriggerFooterRefresh:(id)tvm
{
    @weakify(self);
    if (self.viewModel.tvmType == 0)
    {
        ZCFGV2TableViewModel* tableVM = tvm;
        
        NSDictionary* info = @{@"LoadIndex":@(tableVM.page)};
        [[[tableVM.requestDataCmd
           execute:info]
          deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             tableVM.page += 1;
         } error:^(NSError *error) {
             @strongify(self);
             [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
         } completed:^{
             @strongify(self)
             [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
         }];
    }
    else
    {
        DocumentV2TableViewModel* tableVM = tvm;
        
        NSDictionary* info = @{@"LoadIndex":@(tableVM.page)};
        [[[tableVM.requestDataCmd
           execute:info]
          deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             tableVM.page += 1;
         } error:^(NSError *error) {
             @strongify(self);
             [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
         } completed:^{
             @strongify(self)
             [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
         }];
    }
}

/// 刷新完成事件
- (void)tableViewDidFinishTriggerHeader:(BOOL)isHeader reload:(BOOL)reload tableVM:(id)tvm
{
    NSInteger tag = 0;
    NSInteger page = 0;
    NSInteger lastPage = 0;
    
    if ([tvm isKindOfClass:[ZCFGV2TableViewModel class]])
    {
        ZCFGV2TableViewModel* tableVM = tvm;
        tag = tableVM.tag;
        page = tableVM.page;
        lastPage = tableVM.lastPage;
    }
    else
    {
        DocumentV2TableViewModel* tableVM = tvm;
        tag = tableVM.tag;
        page = tableVM.page;
        lastPage = tableVM.lastPage;
    }
    
    UITableView* findTableView = NULL;
    
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tag)
        {
            findTableView = curTableView;
            
            break;
        }
    }
    
    if (findTableView != NULL)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (reload) {
                [findTableView reloadData];
            }
            if (isHeader) {
                [findTableView.mj_header endRefreshing];
            }
            else{
                [findTableView.mj_footer endRefreshing];
            }
            /// 最后一页隐藏加载控件
            findTableView.mj_footer.hidden = (page>=lastPage);
        });
    }
}

- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(64, 0, 0, 0);
}

/// reload tableView data
- (void)reloadListData:(NSInteger)tag
{
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tag)
        {
            NSLog(@"ReloadData Tag : %d", tag);
            
            if (self.viewModel.tvmType == 0)
            {
                for (ZCFGV2TableViewModel* curTVM in self.viewModel.tableVMs)
                {
                    if (curTVM.tag == tag)
                    {
                        NSLog(@"ReloadData dataSource : %d", curTVM.dataSource.count);
                        
                        break;
                    }
                }
            }
            else
            {
                for (DocumentV2TableViewModel* curTVM in self.viewModel.tableVMs)
                {
                    if (curTVM.tag == tag)
                    {
                        NSLog(@"ReloadData dataSource : %d", curTVM.dataSource.count);
                        
                        break;
                    }
                }
            }
            
            [curTableView reloadData];
            
            break;
        }
    }
}

/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    NSString* strClass = self.viewModel.tvmType == 0 ? NSStringFromClass([ZCFGCell class]) : NSStringFromClass([DocumentV2Cell class]);
    
    return [tableView dequeueReusableCellWithIdentifier:strClass];
}

/// config  data
- (void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    
    if (self.viewModel.tvmType == 0)
    {
        ZCFGCell* curCell = cell;
        ZCFGCellModel* curCellModel = object;
        
        [curCell bindViewModel:curCellModel];
    }
    else
    {
        DocumentV2Cell* curCell = cell;
        DocumentV2CellModel* curCellModel = object;
        
        [curCell bindViewModel:curCellModel];
    }
    
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.viewModel.tvmType == 0)
    {
        ZCFGV2TableViewModel* curTableVM = NULL;
        for (ZCFGV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                curTableVM = curTVM;
                
                break;
            }
        }
        
        if (curTableVM.shouldMultiSections) return curTableVM.dataSource ? curTableVM.dataSource.count : 1;
    }
    else
    {
        DocumentV2TableViewModel* curTableVM = NULL;
        for (DocumentV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                curTableVM = curTVM;
                
                break;
            }
        }
        
        if (curTableVM.shouldMultiSections) return curTableVM.dataSource ? curTableVM.dataSource.count : 1;
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = 0;
    
    if (self.viewModel.tvmType == 0)
    {
        ZCFGV2TableViewModel* curTableVM = NULL;
        for (ZCFGV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                curTableVM = curTVM;
                
                break;
            }
        }
        
        if (curTableVM.shouldMultiSections) return [curTableVM.dataSource[section] count];
        
        return curTableVM.dataSource.count;
    }
    else
    {
        DocumentV2TableViewModel* curTableVM = NULL;
        for (DocumentV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                curTableVM = curTVM;
                
                break;
            }
        }
        
        if (curTableVM.shouldMultiSections) return [curTableVM.dataSource[section] count];
        
        return curTableVM.dataSource.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.viewModel.tvmType == 0)
    {
        ZCFGV2TableViewModel* findTVM = NULL;
        for (ZCFGV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                findTVM = curTVM;
                
                break;
            }
        }
        
        Class cellClass = [ZCFGCell class];
        
        UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
        
        // fetch object
        id object = nil;
        if (findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.section][indexPath.row];
        if (!findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.row];
        
        /// bind model
        [self configureCell:(ZCFGCell*)cell atIndexPath:indexPath withObject:(id)object];
        
        return cell;
    }
    else
    {
        DocumentV2TableViewModel* findTVM = NULL;
        for (DocumentV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                findTVM = curTVM;
                
                break;
            }
        }
        
        Class cellClass = [DocumentV2Cell class];
        
        UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
        
        // fetch object
        id object = nil;
        if (findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.section][indexPath.row];
        if (!findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.row];
        
        /// bind model
        [self configureCell:(DocumentV2Cell*)cell atIndexPath:indexPath withObject:(id)object];
        
        return cell;
    }
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    if (self.viewModel.tvmType == 0)
    {
        for (ZCFGV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (tableView.tag == curTVM.tag)
            {
                return [curTVM.dataSource[indexPath.row] cellHeight];
            }
        }
    }
    else
    {
        for (DocumentV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (tableView.tag == curTVM.tag)
            {
                return [curTVM.dataSource[indexPath.row] cellHeight];
            }
        }
    }
    
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // execute commond
    
    if (self.viewModel.tvmType == 0)
    {
        for (ZCFGV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                ZCFGCellModel* cellModel = curTVM.dataSource[indexPath.row];
                [curTVM.didSelectCommand execute:cellModel];
                
                return;
            }
        }
    }
    else
    {
        for (DocumentV2TableViewModel* curTVM in self.viewModel.tableVMs)
        {
            if (curTVM.tag == tableView.tag)
            {
                DocumentV2CellModel* cellModel = curTVM.dataSource[indexPath.row];
                [curTVM.didSelectCommand execute:cellModel];
                
                return;
            }
        }
    }
}

#pragma mark - 监听事件
- (void)_onBtnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)_onBtnSearch
{
    [self _push2SearchVC];
}

#pragma mark - 跳转
- (void)_push2StwxDetailVCByArticleID:(NSString*)articleID type:(NSInteger)type
{
    if (type == 2)
    {
        DocumentDetailViewModel* vm = [[DocumentDetailViewModel alloc] initWithParams:@{}];
        vm.articleID = articleID;
        DocumentDetailViewController* vc = [[DocumentDetailViewController alloc] initWithViewModel:vm];
        UIViewController* showVC = [UIViewController getCurrentVC];
        
        UINavigationController* navc = showVC.navigationController;
        [navc pushViewController:vc animated:YES];
    }
    else
    {
        StwxDetailViewModel* vm = [[StwxDetailViewModel alloc] initWithParams:@{}];
        //    [vm initStwxDetail:stwxDetailIVM];
        //    vm.isHaveDetailCtrl = NO;
        vm.articleID = articleID;
        StwxDetailViewController* vc = [[StwxDetailViewController alloc] initWithViewModel:vm];
        UIViewController* showVC = [UIViewController getCurrentVC];
        
        UINavigationController* navc = showVC.navigationController;
        [navc pushViewController:vc animated:YES];
    }
}

- (void)_push2SearchVC
{
    TotalSearchViewModel* vm = [[TotalSearchViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"搜索"}];
    vm.cateID = self.viewModel.cateInfoData.cateID;
    TotalSearchViewController* vc = [[TotalSearchViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2AddrPop
{
    DataManager* dm = [DataManager sharedDataManager];
    
    @weakify(self)
    AddrChooserViewModel* vm = [[AddrChooserViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"选择地区"}];
    vm.chooseBlock = ^(ProvinceListData* choosePData)
    {
        @strongify(self);
        
        [self.viewModel resetZoneData:choosePData];
    };
    AddrChooserViewController* vc = [[AddrChooserViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
